package com.urbanski.clipboard.server.action.message;

import java.io.IOException;
import java.util.Collection;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.common.message.EmptyResponse;
import com.urbanski.clipboard.common.message.Message;
import com.urbanski.clipboard.common.message.PauseMessage;
import com.urbanski.clipboard.server.ClientSocket;
import com.urbanski.clipboard.server.ClipboardServer;
import com.urbanski.clipboard.server.session.ServerSession;
import com.urbanski.util.logging.LoggingUtil;

public class PauseMessageHandler extends ServerMessageHandler
{
	private static final Logger LOGGER = Logger.getLogger(PauseMessageHandler.class);

	public PauseMessageHandler(ClientSocket client)
	{
		super(client);
	}

	@Override
	public void handle(Message message)
	{
		PauseMessage pauseMessage = (PauseMessage)message;

		if (pauseMessage.getSessions().isEmpty())
		{
			Collection<ServerSession> clientSessions = ClipboardServer.getSessionsForClient(client.getClientName());
			for (ServerSession s : clientSessions)
			{
				s.pauseClient(client.getClientName());
			}
		}
		else
		{
			Collection<ServerSession> clientSessions = ClipboardServer.getSessionsForClient(client.getClientName());
			for (ServerSession s : clientSessions)
			{
				if (pauseMessage.getSessions().contains(s.getSessionName()))
				{
					s.pauseClient(client.getClientName());
				}
			}
		}

		try
		{
			client.sendResponse(new EmptyResponse());
		}
		catch (IOException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Error sending response", e);
		}
	}

}
